package com.work.keep.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.work.keep.R;
import com.work.keep.adapter.MyOtherUserRecyclerAdapter;
import com.work.keep.base.BaseFragment;
import com.work.keep.datas.FragmentOtherDynamicData;
import com.work.keep.ui.OnReadForLoading;
import com.work.keep.volley.GsonRequest;
import com.work.keep.volley.VolleySingleton;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * * https://api.gotokeep.com/v1.1/people/56999b2d9951948b57b2c53b/photos?limit=18
 * /photos?limit=18
 * fragment_other_user_recycler
 * Created by dllo on 16/1/19.
 */
public class OtherUserPhotoFragment extends BaseFragment implements OnReadForLoading {
    private Context context;
    private RecyclerView recyclerView;
    private VolleySingleton volleySingleton;
    private ImageLoader imageLoader;
    private List<FragmentOtherDynamicData.DataEntity> dataEntities;
    //下拉加载更多用到的网址
    private String lastIdUrl = "";
    private MyOtherUserRecyclerAdapter peoplePhotoAdapter;


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_other_user_recycler, container, false);
        return v;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView = (RecyclerView) view.findViewById(R.id.otherUserRecycler);
    }


    @Override
    protected void init() {
        volleySingleton = VolleySingleton.getInstance();
        imageLoader = volleySingleton._getImageLoader();
        String url = getArguments().get("url") + "/photos?limit=18";
        peoplePhotoAdapter = new MyOtherUserRecyclerAdapter(context);
        recyclerView.setLayoutManager(new GridLayoutManager(context, 2));
        recyclerView.setAdapter(peoplePhotoAdapter);
        GsonRequest<FragmentOtherDynamicData> photoRequest = new GsonRequest<FragmentOtherDynamicData>(url, FragmentOtherDynamicData.class, new Response.Listener<FragmentOtherDynamicData>() {
            @Override
            public void onResponse(FragmentOtherDynamicData response) {
                Log.d("aaaaa", "onr");
                peoplePhotoAdapter.addData(response.getData());
                lastIdUrl = "https://api.gotokeep.com/v1.1/people/" + response.getLastId() + "/photos?limit=18";
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> dynamicHeader = new HashMap<>();
                dynamicHeader.put("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJfaWQiOiI1NjY1MDBlMTYzZGIwYzlmNTdiMTQwYWQiLCJ1c2VybmFtZSI6Iuaeq-WQmyIsImF2YXRhciI6Imh0dHA6Ly93eC5xbG9nby5jbi9tbW9wZW4vc2t3MmhSR3lXRWcwUzV0NzhkMlRVUnFhYjBzcWJ4RXB4S1BLUFpEOXpwbTNJbkIySzRjRnhLVEJsemdDb3VIcGlia3RkRUluQ0NFcGpIS2FHZ1lwRkp6SVRIVU5NYTNpYmYvMCIsImlhdCI6MTQ1MzE2NDEwNCwiZXhwIjoxNDU1NzU2MTA0LCJpc3MiOiJodHRwOi8vd3d3LmdvdG9rZWVwLmNvbS8ifQ.iSPkGXPiR7VG_Fj-z7YDCj2_uuLbecau5bFoUU0iB10");
                dynamicHeader.put("X-X", "486bba2566a02d3ae31ed4445366a873b89cf910");
                dynamicHeader.put("Host", "api.gotokeep.com");
                dynamicHeader.put("If-None-Match", "W/\"d31-zBP8NgaJJvecQ0qMhgeVfw\"");
                return dynamicHeader;
            }
        };
        volleySingleton._addRequest(photoRequest);
    }

    @Override
    public boolean isRead() {
        RecyclerView.Adapter adapter = recyclerView.getAdapter();
//        //对adapter为空的情况 截断
        if (null == adapter) {
            return true;
        }

        int lastItemPosition = adapter.getItemCount() - 1;
        //最后一个可见的recyclerview item
        View lastVisibleView = recyclerView.getChildAt(recyclerView.getChildCount() - 1);
        int lastVisiblePosition = recyclerView.getChildAdapterPosition(lastVisibleView);
        View firstVisibleView = recyclerView.getChildAt(0);
        int firstVisiblePosition = recyclerView.getChildAdapterPosition(firstVisibleView);

        /**
         * This check should really just be: lastVisiblePosition == lastItemPosition, but ListView
         * internally uses a FooterView which messes the positions up. For me we'll just subtract
         * one to account for it and rely on the inner condition which checks getBottom().
         */
        if (lastVisiblePosition >= lastItemPosition - 1) {
            int childIndex = lastVisiblePosition - firstVisiblePosition;
            int childCount = recyclerView.getChildCount();
            int index = Math.min(childIndex, childCount - 1);
            if (lastVisibleView != null) {
                return lastVisibleView.getBottom() <= recyclerView.getBottom();
            }
        }
        return false;
    }
}
